package cc.ufinity.networkdiagnose.widget;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import cc.ufinity.networkdiagnose.adapter.TaskTestListAdapter;
import cc.ufinity.networkdiagnose.app.GlobalApp;
import cc.ufinity.networkdiagnose.manager.Account;
import cc.ufinity.networkdiagnose.manager.DBManager;
import cc.ufinity.networkdiagnose.manager.MessageWhat;
import cc.ufinity.networkdiagnose.manager.NetworkManager;
import cc.ufinity.networkdiagnose.manager.Task;
import cc.ufinity.networkdiagnose.manager.TelManager;
import cc.ufinity.networkdiagnose.manager.WebAuthManager;
import cc.ufinity.networkdiagnose.manager.WlanManager;
import cc.ufinity.networkdiagnose.util.StringUtils;
import cc.ufinity.networkdiagnose.view.R;

public class Task_Test_Widget extends GeneralTestWidget {
	public final static String PREFS_NAME = "mymobile";
    public final static String PREFS_KEY = "number";
	
	public static Activity ctx;
	private static String TAG = "TaskWidget";
	private ListView taskListView;
	private List<Task> tasks = null;
	private TelManager tm;
	private Handler handler;
	private String myPhoneNumber;
	private List<Map<String, Object>> datas;
	private TaskTestListAdapter tAdapter = null;
	private ImageView image1 = null, image2 = null;
	private ProgressBar pb1 = null, pb2 = null;
	private Button begin_test = null;
	private TextView tv_progress1 = null, tv_progress2 = null;
	private LinearLayout linearlayout = null; 
	private int testNum;
    private WlanManager wlanManager;
	private boolean connected = false;
	private boolean connected2 = false;
	private Thread thread;
	private TextView titleView; 
	private Task task;
	private boolean btnClick = false; 
	public Task_Test_Widget(Activity context) {
		super(context);
		this.ctx = context;
		wlanManager = new WlanManager(ctx);
		GlobalApp.clearAll();
		task = (Task) ctx.getIntent().getSerializableExtra(TAG_REFER_TASK);//获取任务
		if(task == null) {
			System.out.println("task传值失败" );
		} else {
			System.out.println("网络类型：" + task.selNetType+":"+task.acIp);
		}
		
		inflate(context, R.layout.task_test_widget, this);
		linearlayout = (LinearLayout)this.findViewById(R.id.progress_linearlayout);
		image1 = new ImageView(ctx);
		image1.setBackgroundResource(R.drawable.test_before);
		image2 = new ImageView(ctx);
		image2.setBackgroundResource(R.drawable.test_after);
		linearlayout.addView(image1, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		pb2 = (ProgressBar)findViewById(R.id.progress2);
		tv_progress1 = (TextView)findViewById(R.id.tv_progress1);
		tv_progress2 = (TextView)findViewById(R.id.tv_progress2);
		titleView = (TextView)findViewById(R.id.task_test_title);
		String from = ctx.getIntent().getStringExtra("from");
    	from = from == null?"":from;
    	if(from.equals("TestWidget")) {
    		titleView.setText(R.string.test_task_title);
    	}else {
    		titleView.setText(task.taskType);
		} 
		begin_test = (Button)findViewById(R.id.begin_tesk);
		begin_test.setText("测试中...");
		begin_test.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (btnClick) {
					ctx.setContentView(new TaskResult(ctx));
					btnClick = false;
				}
				ctx.getIntent().putExtra(TAG_REFER_TASK, task);
			   // new HttpTestWidgetProxy(ctx);
				
			}
		});
		
		taskListView = (ListView) this.findViewById(R.id.taskTestListView);
		taskListView.setOnItemClickListener(new OnItemClickListener() {

			@SuppressWarnings("unchecked")
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Map<String, Object> r = (Map<String, Object>) taskListView
						.getAdapter().getItem(position);
				
				Log.d("结果查看", "详细信息: " + r.toString());
			}
		});
		
		handler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case MessageWhat.TASK_LIST_LOADED_SUCCESS:
					init();
					dismissMessageDialog();
					break;
				case MessageWhat.TASK_LIST_LOADED_FAILED:
					dismissMessageDialog();
					showMessage(ctx, "获取任务列表失败.");
					break;
				case 2:
					showMessage(ctx, "本机手机号码无法获取.");
					dismissMessageDialog();
					break;
				case MessageWhat.WIFI_SUCESS_CONNECTED:  
					dismissMessageDialog(); 
                	start();
                    break;
				}
			}
		};

		tm = new TelManager(ctx);
		tm.setHandler(handler); 
//		start();
		wlanManager.setHandler(handler); 
		connectNetWork();
	}   
 
	// 广播接收器
	/*class ActivityBroadcastReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			String testflag =intent.getStringExtra("testIndex"); 
			Message msg = new Message();
			System.out.println(testflag+"= = = =  收到广播   = = = ="+testNum);
			if(datas!=null&&datas.size()>0 && taskListView!=null && taskListView.getAdapter()!=null){
				// TODO Auto-generated method stub
				if (doNextTaskBroadCast.equals(intent.getAction()) && testflag.equals("start0")) {
					System.out.println(testflag+"= = = =  收到广播0   = = = ="+testNum);
					msg.arg1 = testNum;
//					updateHandler.sendMessage(msg);
					Object tempObject =  taskListView.getAdapter().getItem(testNum);
					Map<String, Object> t2 = tempObject==null?null:(Map<String, Object>) tempObject; 
					System.out.println(testflag+"= = = =  收到广播0000   = = = ="+testNum);
					if(t2!=null && t2.get("taskSkip")!=null && t2.get("taskSkip").equals("0")) {
						if(task.taskType!=null && task.taskType.equals("巡检测试"))
						{
							FtpTestProxyWidget.doNextTaskBroadCast = doNextTaskBroadCast;
							FtpTestProxyWidget.taskFlag = 0;
							FtpTestProxyWidget.testFlag = 0;
							new FtpTestProxyWidget(ctx);
						}
						else
						{		System.out.println(testflag+"= = = =  收到广播00001   = = = ="+testNum);
							HttpTestWidgetProxy.doNextTaskBroadCast = doNextTaskBroadCast;
							HttpTestWidgetProxy.taskFlag = 0;
							HttpTestWidgetProxy.testFlag = 0;
							new HttpTestWidgetProxy(ctx);
//						}
					} else  {
						if(task.taskType!=null && task.taskType.equals("巡检测试"))
						{
							mSendBroadcast(ctx,"ftpTest0");
							GlobalApp.result_FTP_test=new StringBuffer("\n\nFTP测试项已跳过");
						}
						else  
						{		System.out.println(testflag+"= = = =  收到广播00002   = = = ="+testNum);
						
							mSendBroadcast(ctx,"httpTest0");
							GlobalApp.result_HTTP_test=new StringBuffer("\n\nHTTP测试项已跳过");
//						}
					}
				}else if (doNextTaskBroadCast.equals(intent.getAction()) && testflag.equals("httpTest0")) {
					System.out.println("= = = =  收到广播1   = = = =");
					msg.arg1 = testNum;
					testNum = testNum +1;
					updateHandler.sendMessage(msg);
					Object tempObject =  taskListView.getAdapter().getItem(testNum);
					Map<String, Object> t2 = tempObject==null?null:(Map<String, Object>) tempObject;
					if(t2!=null && t2.get("taskSkip")!=null && t2.get("taskSkip").equals("0")) {
						FtpTestProxyWidget.taskFlag = 0;
						FtpTestProxyWidget.testFlag = 0;
						FtpTestProxyWidget.doNextTaskBroadCast = doNextTaskBroadCast;
						new FtpTestProxyWidget(ctx);
					}else {
						mSendBroadcast(ctx,"ftpTest0");
						GlobalApp.result_FTP_test=new StringBuffer("\n\nFTP测试项已跳过");
//						if(task.selNetType == ConnectivityManager.TYPE_WIFI)
//							mSendBroadcast(ctx,"ftpTest0");
//						else  
//							mSendBroadcast(ctx,"pingTest0");
					}
				}else if (doNextTaskBroadCast.equals(intent.getAction()) && testflag.equals("ftpTest0")) {
					System.out.println("= = = =  收到广播2   = = = =");
					msg.arg1 = testNum;
					testNum = testNum +1;
					updateHandler.sendMessage(msg);
					Object tempObject =  taskListView.getAdapter().getItem(testNum);
					Map<String, Object> t2 = tempObject==null?null:(Map<String, Object>) tempObject;
					if(t2!=null && t2.get("taskSkip")!=null && t2.get("taskSkip").equals("0")) {
						PingWidgetProxy.taskFlag = 0;
						PingWidgetProxy.testFlag = 0;
						PingWidgetProxy.doNextTaskBroadCast = doNextTaskBroadCast;
						new PingWidgetProxy(ctx);
					} else  {
						mSendBroadcast(ctx,"pingTest0");
					}
				}else if (doNextTaskBroadCast.equals(intent.getAction()) && testflag.equals("pingTest0")) {
					System.out.println("= = = =  收到广播3   = = = =");
					msg.arg1 = testNum;
					testNum = testNum +1; 
					updateHandler.sendMessage(msg);
					Object tempObject =  taskListView.getAdapter().getItem(testNum);
					Map<String, Object> t2 = tempObject==null?null:(Map<String, Object>) tempObject;
					if(task.selNetType == ConnectivityManager.TYPE_WIFI){
						System.out.println(testflag+"= = = = LGDDD   = = = ="+testNum);
						if(t2!=null && t2.get("taskSkip")!=null && t2.get("taskSkip").equals("0")) {
							ApRelevanceTestWidgetProxy.taskFlag = 0;
							ApRelevanceTestWidgetProxy.testFlag = 0;
							ApRelevanceTestWidgetProxy.doNextTaskBroadCast = doNextTaskBroadCast;
							new ApRelevanceTestWidgetProxy(ctx);
							System.out.println(testflag+"= = = = LGDDD1   = = = ="+testNum);
						} else {
							mSendBroadcast(ctx,"ApRelevanceTest0");
							GlobalApp.result_AP_test=new StringBuffer("\n\nAP关联测试项已跳过");
						}
					}else {
						if(t2!=null && t2.get("taskSkip")!=null && t2.get("taskSkip").equals("0")) {
							SnrTestWidgetProxy.taskFlag = 0;
							SnrTestWidgetProxy.testFlag = 0;
							SnrTestWidgetProxy.doNextTaskBroadCast = doNextTaskBroadCast;
							new SnrTestWidgetProxy(ctx);
						} else {
							mSendBroadcast(ctx,"snrTest0");
							GlobalApp.result_SNR_test=new StringBuffer("\n\n信噪比测试项已跳过");
						}
					}
					
				}else if (doNextTaskBroadCast.equals(intent.getAction()) && testflag.equals("ApRelevanceTest0")) {
					System.out.println("= = = =  收到广播31   = = = =");
					msg.arg1 = testNum;
					testNum = testNum +1;
					updateHandler.sendMessage(msg);
					Object tempObject =  taskListView.getAdapter().getItem(testNum);
					Map<String, Object> t2 = tempObject==null?null:(Map<String, Object>) tempObject;
					if(t2!=null && t2.get("taskSkip")!=null && t2.get("taskSkip").equals("0")&&task.scanResult!=null && task.scanResult.SSID!=null &&task.scanResult.SSID.equals(WlanManager.SSID_CMCC)) {
						WebauthTestWidgetProxy.taskFlag = 0;
						WebauthTestWidgetProxy.testFlag = 0;
						WebauthTestWidgetProxy.doNextTaskBroadCast = doNextTaskBroadCast;
						new WebauthTestWidgetProxy(ctx);
					} else {
						mSendBroadcast(ctx,"WebauthTestWidget0");
						GlobalApp.result_WEB_test=new StringBuffer("\n\nWeb认证测试条件不满足");
					}
				}else if (doNextTaskBroadCast.equals(intent.getAction()) && testflag.equals("WebauthTestWidget0")) {
					webAuth();
					System.out.println("= = = =  收到广播4   = = = =");
					msg.arg1 = testNum;
					testNum = testNum +1;
					Task  task1 = (Task) ctx.getIntent().getSerializableExtra(TAG_REFER_TASK);//获取任务
					if(task1 !=null && task1.scanResult!=null && task1.scanResult.SSID!=null &&task1.scanResult.SSID.equals(WlanManager.SSID_CMCC)&& (task1.webOffSuccessRate == null || task1.webOffSuccessRate.equals("0"))&& (task1.webSuccessRate ==null|| task1.webSuccessRate.equals("0")) )
						showMessage(ctx, "web认证过程失败");
					updateHandler.sendMessage(msg);
					Object tempObject =  taskListView.getAdapter().getItem(testNum);
					Map<String, Object> t2 = tempObject==null?null:(Map<String, Object>) tempObject;
					if(t2!=null && t2.get("taskSkip")!=null && t2.get("taskSkip").equals("0")) {
						if(task.taskType!=null && task.taskType.equals("巡检测试"))
						{
							SnrTestWidgetProxy.taskFlag = 0;
							SnrTestWidgetProxy.testFlag = 0;
							SnrTestWidgetProxy.doNextTaskBroadCast = doNextTaskBroadCast;
							new SnrTestWidgetProxy(ctx);
						}
						else
						{
							PeapTestWidgetProxy.taskFlag = 0;
							PeapTestWidgetProxy.testFlag = 0;
							PeapTestWidgetProxy.doNextTaskBroadCast = doNextTaskBroadCast;
							new PeapTestWidgetProxy(ctx);
						}
					} else  {
						if(task.taskType!=null && task.taskType.equals("巡检测试"))
						{
							mSendBroadcast(ctx,"snrTest0");
							GlobalApp.result_SNR_test=new StringBuffer("\n\n信噪比测试项已跳过");
						}
						else
						{
							mSendBroadcast(ctx,"peapAuthTest0");
							GlobalApp.result_PEAP_test=new StringBuffer("\n\nPEAP测试项已跳过");
						}
					}
				} else if (doNextTaskBroadCast.equals(intent.getAction()) && testflag.equals("peapAuthTest0")) {
					System.out.println("= = = =  收到广播5   = = = =");
					msg.arg1 = testNum;
					testNum = testNum +1;
					updateHandler.sendMessage(msg);
					Object tempObject =  taskListView.getAdapter().getItem(testNum);
					Map<String, Object> t2 = tempObject==null?null:(Map<String, Object>) tempObject;
					if(t2!=null && t2.get("taskSkip")!=null && t2.get("taskSkip").equals("0")) {
						SimTestWidgetProxy.taskFlag = 0;
						SimTestWidgetProxy.testFlag = 0;
						SimTestWidgetProxy.doNextTaskBroadCast=doNextTaskBroadCast;
						new SimTestWidgetProxy(ctx);
					} else {
						mSendBroadcast(ctx,"simAuthTest0");
						GlobalApp.result_SIM_test=new StringBuffer("\n\nSIM测试项已跳过");
					}
				}else if (doNextTaskBroadCast.equals(intent.getAction()) && testflag.equals("simAuthTest0")) {
					System.out.println("= = = =  收到广播6   = = = =");
					msg.arg1 = testNum;
					testNum = testNum +1;
					updateHandler.sendMessage(msg);
					Object tempObject =  taskListView.getAdapter().getItem(testNum);
					Map<String, Object> t2 = tempObject==null?null:(Map<String, Object>) tempObject;
					if(t2!=null && t2.get("taskSkip")!=null && t2.get("taskSkip").equals("0")) {
						SegregateTestWidgetProxy.taskFlag = 0;
						SegregateTestWidgetProxy.testFlag = 0;
						SegregateTestWidgetProxy.doNextTaskBroadCast=doNextTaskBroadCast;
						new SegregateTestWidgetProxy(ctx);
					} else {
						mSendBroadcast(ctx,"segregateTest0");
						GlobalApp.result_SEGREGATE_test=new StringBuffer("\n\n隔离测试项已跳过");
					}
				}else if (doNextTaskBroadCast.equals(intent.getAction()) && testflag.equals("segregateTest0")) {
					System.out.println("= = = =  收到广播7   = = = =");
					msg.arg1 = testNum;
					testNum = testNum +1;
					updateHandler.sendMessage(msg);
					Object tempObject =  taskListView.getAdapter().getItem(testNum);
					Map<String, Object> t2 = tempObject==null?null:(Map<String, Object>) tempObject;
					if(t2!=null && t2.get("taskSkip")!=null && t2.get("taskSkip").equals("0")) {
						RoamTestWidgetProxy.taskFlag = 0;
						RoamTestWidgetProxy.testFlag = 0;
						RoamTestWidgetProxy.doNextTaskBroadCast=doNextTaskBroadCast;
						new RoamTestWidgetProxy(ctx);
					} else  {
						mSendBroadcast(ctx,"roamPingTest0");
						GlobalApp.result_ROAM_test=new StringBuffer("\n\n漫游测试项已跳过");
					}
				}else if (doNextTaskBroadCast.equals(intent.getAction()) && testflag.equals("roamPingTest0")) {
					System.out.println("= = = =  收到广播8   = = = =");
					msg.arg1 = testNum;
					testNum = testNum +1;
					updateHandler.sendMessage(msg);
					Object tempObject =  taskListView.getAdapter().getItem(testNum);
					Map<String, Object> t2 = tempObject==null?null:(Map<String, Object>) tempObject;
					if(t2!=null && t2.get("taskSkip")!=null && t2.get("taskSkip").equals("0")) {
						SnrTestWidgetProxy.taskFlag = 0;
						SnrTestWidgetProxy.testFlag = 0;
						SnrTestWidgetProxy.doNextTaskBroadCast=doNextTaskBroadCast;
						new SnrTestWidgetProxy(ctx);
					} else  {
						mSendBroadcast(ctx,"snrTest0");
						GlobalApp.result_SNR_test=new StringBuffer("\n\n信噪比测试项已跳过");
					}
				}else if (doNextTaskBroadCast.equals(intent.getAction()) && testflag.equals("snrTest0")) {
					System.out.println("= = = =  收到广播9   = = = =");
					msg.arg1 = testNum;  
					testNum = testNum +1;  
					updateHandler.sendMessage(msg);
					Object tempObject =  taskListView.getAdapter().getItem(testNum);
					Map<String, Object> t2 = tempObject==null?null:(Map<String, Object>) tempObject;
					if(t2!=null && t2.get("taskSkip")!=null && t2.get("taskSkip").equals("0")) {
						RssiTestWidgetProxy.taskFlag = 0;     
						RssiTestWidgetProxy.testFlag = 0;  
						RssiTestWidgetProxy.doNextTaskBroadCast=doNextTaskBroadCast;
						new RssiTestWidgetProxy(ctx);
					} else {
						mSendBroadcast(ctx,"rssiTest0");
						GlobalApp.result_SRRI_test=new StringBuffer("\n\n信号强度测试项已跳过");
					}
				}else if (doNextTaskBroadCast.equals(intent.getAction()) && testflag.equals("rssiTest0")) {
					System.out.println("= = = =  收到广播10   = = = =");
					msg.arg1 = testNum;
					testNum = testNum+1;
					updateHandler.sendMessage(msg); 
				}
				System.err.println(testNum+"==============================#########################");
			}else {
			}
		}
	}
*/
	Thread updateThread = new Thread() {

		@Override
		public void run() {
			// TODO Auto-generated method stub 
			pb2.setMax(datas.size());
		}
		
	};
	Handler updateHandler = new Handler() {
		private String testingName = "";
		public void handleMessage(Message msg) {
			if(msg.arg1 == -1) {
				ProgressBar pb = new ProgressBar(ctx);
				pb.setVisibility(VISIBLE);
				linearlayout.removeAllViews();
				linearlayout.addView(pb, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
				@SuppressWarnings("unchecked")
				Map<String, Object> t = (Map<String, Object>) taskListView
					.getAdapter().getItem(msg.arg1+1);
				testingName =(t==null)?"": (String)t.get("taskName");
				if(t!=null && t.get("taskSkip")!=null &&t.get("taskSkip").equals("0")) {
					t.put("taskState", "3");
				} else if(t!=null && t.get("taskSkip")!=null &&t.get("taskSkip").equals("1")) {
					System.out.println(testingName + " 已跳过");
				}
				
			} else if(msg.arg1 < datas.size()-1){
				@SuppressWarnings("unchecked")
				Map<String, Object> t1 = (Map<String, Object>) taskListView
					.getAdapter().getItem(msg.arg1);
				@SuppressWarnings("unchecked")
				Map<String, Object> t2 = (Map<String, Object>) taskListView
					.getAdapter().getItem(msg.arg1+1);
				testingName =(t2==null)?"":(String)t2.get("taskName");
				if(t1!=null && t1.get("taskSkip")!=null && t1.get("taskSkip").equals("0")) {
					t1.put("taskState", "1");
				} else if(t1!=null && t1.get("taskSkip")!=null &&t1.get("taskSkip").equals("1")) {
					System.out.println(t1.get("taskName") + " 已跳过");
				}
				if(t2!=null && t2.get("taskSkip")!=null &&t2.get("taskSkip").equals("0")) {
					t2.put("taskState", "3");
				} else if(t2!=null && t2.get("taskSkip")!=null && t2.get("taskSkip").equals("1")) {
					System.out.println(t2.get("taskName") + " 已跳过");
				}
			} else if(msg.arg1 == datas.size()-1) {
				@SuppressWarnings("unchecked")
				Map<String, Object> t = (Map<String, Object>) taskListView
					.getAdapter().getItem(msg.arg1);
				if(t!=null && t.get("taskSkip")!=null &&t.get("taskSkip").equals("0")) {
					t.put("taskState", "1");
				} else if(t!=null && t.get("taskSkip")!=null &&t.get("taskSkip").equals("1")) {
					System.out.println(t.get("taskName") + " 已跳过");
				}
			}
			
			if(msg.arg1+1 >= datas.size()) {
				tv_progress2.setText("检测完毕");
				btnClick = true;
				begin_test.setText("查看结果");
				linearlayout.removeAllViews();
				linearlayout.addView(image2, new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT)); 
				//=============================自动跳转到测试结果页面上传结果
				if (btnClick) {
					
					ctx.setContentView(new Test_Task_Widget_TD(ctx));
					
				//	ctx.setContentView(new TaskResult(ctx));
					btnClick = false;
				}
				ctx.getIntent().putExtra(TAG_REFER_TASK, task);
		    	//================================================================
			 	
			} else {
				tv_progress2.setText("正在检测第" + (msg.arg1+2) + "项：" + testingName);
			}
			
			tv_progress1.setText("总进度：" + 100*(msg.arg1+1)/datas.size() + "%");
			pb2.setProgress(msg.arg1+1);
			tAdapter.notifyDataSetChanged();  //更新Adapter
		}
		
	}; 
	public void webAuth(){
		if(task.scanResult != null && task.scanResult.SSID.equals(WlanManager.SSID_CMCC)){
			WebAuthManager wManager = new WebAuthManager(ctx);
			String  defaultUrl = ctx.getResources().getString(R.string.default_url);
	        DBManager db = new DBManager(ctx);
			Account config = db.getAccount(); 
			String userName ="",pwd="";
			if(null != config){ 
//				String USER[]=AccountConfigWidget.stringAnalytical(config.userName);
//				String PWD[]=AccountConfigWidget.stringAnalytical(config.password);
				userName = config.userName;
				pwd = config.password; 
//				userName = USER[0];
//				pwd = PWD[0];
				wManager.auth(defaultUrl, userName, pwd);
			}else {
				showMessage(ctx, "WEB认证错误，请检查账号配置.");
			}
			db.release();
			 // 登录认证
	      
		}
	}
	public void start() {
		webAuth();
		if (NetworkManager.detectNetworkConnectivity(ctx) == -1) {
			showMessage(ctx, "无法连接至因特网.");
			return;
		}
		 myPhoneNumber = tm.getPhoneNumber();
		if (StringUtils.isEmpty(myPhoneNumber)) {
			showMessage(ctx, "获取本机号码失败,请输入.");
			showInputDialog();
			return;
		} else {
			loadTaskList();
		}
	}
	 private void connectNetWork(){
		   showMessageDialog(ctx, "正在连接网络..."); 
		   thread = new Thread() { 
		        @Override
		        public void run() {
		                if (!connected) { 
		                    connected = true;
		                    if(task.selNetType == ConnectivityManager.TYPE_WIFI){
			                     wlanManager.setMobileDataEnabled(false);
		                    	 if(wlanManager.checkNetworkType() != 1){
		                    		 System.err.println("=====================1");
			                    	 wlanManager.openWifi();
					                 wlanManager.connect(task.scanResult);
		                    	 }else {
					                 wlanManager.sendMsg(MessageWhat.WIFI_SUCESS_CONNECTED);
								 }
		                    }else {
		                    	System.err.println("=====================2");
		                    	wlanManager.setMobileDataEnabled(true);
							}
		                }
		        	    while (!connected2) {
		        	    	 if(wlanManager.checkNetworkType() == 3){
			                    	System.err.println("=====================3");
				                	connected2 = true;
				                	wlanManager.sendMsg(MessageWhat.WIFI_SUCESS_CONNECTED);
				                }
						} 
		            }  
		        };

	    	thread.start();
	    }

	private void showInputDialog() {
		LayoutInflater factory = LayoutInflater.from(ctx);
		final View dialogView = factory.inflate(
				R.layout.input_phone_num_dialog, null);
		final EditText inputText = (EditText) dialogView
				.findViewById(R.id.phoneNumEditText);
		AlertDialog.Builder inputBuilder = new AlertDialog.Builder(ctx);
		inputBuilder.setTitle("提示");
		//inputBuilder.setIcon(R.drawable.smile);
		inputBuilder.setView(dialogView);
		inputBuilder.setPositiveButton("确定",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						if (StringUtils.isEmpty(inputText.getText().toString())) {
							try {
								Field field = dialog.getClass().getSuperclass()
										.getDeclaredField("mShowing");
								field.setAccessible(true);
								field.set(dialog, false);
							} catch (Exception e) {
								e.printStackTrace();
							}
							showMessage(ctx, "请输入本机号码");
						} else {
							try {
								Field field = dialog.getClass().getSuperclass()
										.getDeclaredField("mShowing");
								field.setAccessible(true);
								field.set(dialog, true);
							} catch (Exception e) {
								e.printStackTrace();
							}
							myPhoneNumber = inputText.getText().toString();
							SharedPreferences settings = ctx.getSharedPreferences(PREFS_NAME,0);
				            SharedPreferences.Editor editor = settings.edit();
				            editor.putString(PREFS_KEY, myPhoneNumber);
				            editor.commit();   //保存手机号码
				            
							dialog.cancel();
							loadTaskList();
						}
					}
				});
		inputBuilder.setNegativeButton("取消", 
				new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				try {
					Field field = dialog.getClass().getSuperclass()
							.getDeclaredField("mShowing");
					field.setAccessible(true);
					field.set(dialog, true);
				} catch (Exception e) {
					e.printStackTrace();
				}
				dialog.cancel();
			}
		});
		
		Dialog dialog = inputBuilder.create();
		dialog.show();
	}

	private void loadTaskList() {
		//this.showMessageDialog(ctx, "正在加载任务列表...");
		new Thread() {
			public void run() {
				getTasks();
			}
		}.start();
	}

	private void init() {
	 	tAdapter = new TaskTestListAdapter(ctx, datas);
		taskListView.setAdapter(tAdapter);
		task.startTime = StringUtils.getDateTime();
		testNum = 0; 
		pb2.setMax(datas.size());
		Message msg = new Message();
		msg.arg1 = -1;
		updateHandler.sendMessage(msg);

	}
	
	private List<Map<String, Object>> getTasks() {
		List<Map<String, Object>> res = new ArrayList<Map<String, Object>>();

		try {
			tasks = new ArrayList<Task>();
			
			Task tk0 = new Task();  Task tk1 = new Task();
			Task tk2 = new Task();  Task tk3 = new Task();
			Task tk4 = new Task();  Task tk5 = new Task();
			Task tk6 = new Task();  Task tk7 = new Task();
			Task tk8 = new Task();  Task tk9 = new Task();
			Task tk = new Task();
			tk0.taskName = "HTTP测试";  tk1.taskName = "FTP测试";
			tk2.taskName = "PING测试";  tk3.taskName = "AP关联";
			tk4.taskName = "WEB认证";  tk5.taskName = "PEAP认证";
			tk6.taskName = "SIM认证";  tk7.taskName = "隔离测试";
			tk8.taskName = "漫游测试";  tk9.taskName = "信噪比测试";
			tk.taskName = "信号强度RSSI"; 
			if(task.selNetType == ConnectivityManager.TYPE_WIFI) {
				 tasks = new ArrayList<Task>();
//				 if(task.taskType.equals("验收测试"))
				 tasks.add(tk0); 
				 tasks.add(tk1);
				 tasks.add(tk2);  
				 tasks.add(tk3);
				 tasks.add(tk4); 
				 if(task.taskType.equals("验收测试"))
						tasks.add(tk5);
				 if(task.taskType.equals("验收测试"))
					tasks.add(tk6);  
				 if(task.taskType.equals("验收测试"))
					tasks.add(tk7);
				 if(task.taskType.equals("验收测试"))
					tasks.add(tk8);
				 tasks.add(tk9);
				 tasks.add(tk);
		   }else if(task.selNetType == ConnectivityManager.TYPE_MOBILE || task.selNetType == ConnectivityManager.TYPE_MOBILE_MMS) {
			     tasks = new ArrayList<Task>();
//				 if(task.taskType.equals("验收测试"))
				 tasks.add(tk0); 
				 tasks.add(tk1);  
				 tasks.add(tk2);
				 tasks.add(tk9);  
				 tasks.add(tk); 
			}
			
			
			Map<String, Object> t = null;
			for (Task task : tasks) {
				t = new HashMap<String, Object>();
				t.put("taskName", task.taskName);
				t.put("taskState", "0");  //检测状态
				t.put("taskSkip", "0");   //是否跳过
				
				res.add(t);
			}
			datas = res;
			Message e = new Message();
			e.what = MessageWhat.TASK_LIST_LOADED_SUCCESS;
			handler.sendMessage(e);

		} catch (Exception e) { 
			Message e1 = new Message();
			e1.what = MessageWhat.TASK_LIST_LOADED_FAILED;
			handler.sendMessage(e1);
		}
		return res;
	}

}
